package com.itheima.mobilesafe69.db.dao;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

/**
 * @author qbc
 * 查询归属数据库,获取电话所在位置
 */
public class AddressDao {
	private static final String tag = "AddressDao";
	public static String path = "data/data/com.itheima.mobilesafe69/files/address.db";
	public static String address="未知号码";
	public static String queryAddress(String phone){
		//1,获取数据库操作对象
		SQLiteDatabase db = SQLiteDatabase.openDatabase(path,null,SQLiteDatabase.OPEN_READONLY);
		//正则表达式(专业)匹配手机号
		String regularExpression = "^1[3-8]\\d{9}";
		//是否匹配此正则表达式
		if(phone.matches(regularExpression)){
			//2,如果获取此号码是手机号码,截取其前7位,用作查询
			String subPhone = phone.substring(0, 7);
			//3,通过db查询数据库,查询subPhone数据
			Cursor cursor = db.query(
					"data1", new String[]{"outkey"}, "id = ?", new String[]{subPhone}, null, null, null);
			//4,如果游标能够移动到下一个节点,查询到了数据
			if(cursor.moveToNext()){
				String outkey = cursor.getString(0);
				//5,查询表2,已outkey作为外键的参数值
				Cursor indexCursor = db.query(
						"data2", new String[]{"location"}, "id = ?", new String[]{outkey}, null, null, null);
				if(indexCursor.moveToNext()){
					address = indexCursor.getString(0);
				}else{
					address = "未知号码";
				}
				indexCursor.close();
			}
			cursor.close();
			//关闭数据库连接
			db.close();
		}else{
			Log.i(tag, "不是手机号码.......................");
			int length = phone.length();
			switch (length) {
			case 3:
				address = "报警电话";
				break;
			case 4:
				address = "模拟器";
				break;
			case 7:
				address = "本地号码";
				break;
			case 8:
				address = "本地号码";
				break;
			case 11:
				//11	区号+座机号码	3+8	
				String area = phone.substring(1, 3);
				Cursor cursor = db.query("data2", 
						new String[]{"location"}, "area = ?", new String[]{area}, null, null, null);
				if(cursor.moveToNext()){
					address = cursor.getString(0);
				}else{
					address = "未知号码";
				}
				cursor.close();
				db.close();
				break;
			case 12:
				//12	区号+座机号码	4+8	
				String area2 = phone.substring(1, 4);
				Cursor cursor2 = db.query("data2", 
						new String[]{"location"}, "area = ?", new String[]{area2}, null, null, null);
				if(cursor2.moveToNext()){
					address = cursor2.getString(0);
				}else{
					address = "未知号码";
				}
				cursor2.close();
				db.close();
				break;
			default:
				address = "未知号码";
				break;
			}
		}
		return address;
	}
}
